package com.lyun.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

// 1. 使用Order注解，设置执行顺序
@Order(-1)
@Component
@Slf4j
// 2. 要实现GlobalFilter声明全局过滤器
public class AuthorizeFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
//        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        MultiValueMap<String, String> params = exchange.getRequest().getHeaders();
        HttpMethod method = exchange.getRequest().getMethod();
        RequestPath path = exchange.getRequest().getPath();
        log.info("请求路径：{} {}", method, path);
        boolean flag = ispass(path);
        if (flag) {
            return chain.filter(exchange);
        }

        // 2.获取authorization参数
        String auth = params.getFirst("Authorization");

        if (StringUtils.hasText(auth)) {
            return chain.filter(exchange);
        }

        // 4.拦截
        // 4.1.禁止访问，设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2.结束处理
        return exchange.getResponse().setComplete();
    }

    private boolean ispass(RequestPath path) {
        String[] pass = {"/user/login"
                , "/user/loginVerification"};
        for (String s : pass) {
            if (path.toString().equals(s)) {
                return true;
            }
        }
        return false;
    }
}
